package com.kq.tallybookl.database;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

import com.kq.tallybookl.R;
import com.kq.tallybookl.activity.PreferencesActivity;
import com.kq.tallybookl.item.MenoItem;
import com.kq.tallybookl.util.GetIMEI;
import com.kq.tallybookl.util.GetMD5;

import net.sqlcipher.Cursor;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteException;
import net.sqlcipher.database.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据库操作管理类
 *
 * Created by Kq on 2016/4/29.
 */
public class FakeManager {

    private static final String[] COLUMNS = { FakeDBHelper.TITLE_COL,
            FakeDBHelper.TIMESTAMP_COL, FakeDBHelper.DETAILS_COL,};

    private static final String[] COUNT_COLUMN = { "COUNT(1)" };

    private static final String[] ID_COL_PROJECTION = { FakeDBHelper.ID_COL };
    private static final String[] ID_DETAIL_COL_PROJECTION = { FakeDBHelper.ID_COL,
            FakeDBHelper.DETAILS_COL };

    private static final String[] PASSWORD_COLUMNS = { FakeDBHelper.LOGIN_PASSWORD};

    private final Activity activity;

    private String db_key;

    public FakeManager(Activity activity) {
        this.activity = activity;
        // 获取数据库密码
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(activity);
        db_key = prefs.getString(
                PreferencesActivity.DB_KEY, null);
        // 加载数据库
        SQLiteDatabase.loadLibs(activity);
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        try {
            if (db_key == null){
                db_key = GetMD5.getMD5(GetIMEI.getIMEI(activity));
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString(PreferencesActivity.DB_KEY,db_key);
                editor.commit();
            }
            SQLiteDatabase db = helper.getWritableDatabase(db_key);
            db.close();
        }catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        }
    }

    // 查询是否创建密码
    public boolean hasLoginPassword(){
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getReadableDatabase(db_key);
            cursor = db.query(FakeDBHelper.PASSWORD_TABLE_NAME, COUNT_COLUMN, null,
                    null, null, null, null);
            cursor.moveToFirst();
            return cursor.getInt(0) > 0;
        } catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
            return false;
        }finally {
            close(cursor, db);
        }
    }

    // 添加密码
    public void addLoginPassword(String password) {
        ContentValues values = new ContentValues();
        values.put(FakeDBHelper.LOGIN_PASSWORD, password);

        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase(db_key);
            // Insert the new entry into the DB.
            db.insert(FakeDBHelper.PASSWORD_TABLE_NAME, FakeDBHelper.LOGIN_PASSWORD, values);
        } catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        }finally {
            close(null, db);
        }
    }

    // 获取密码
    public String getLoginPassword() {
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        String password = null;
        try {
            db = helper.getReadableDatabase(db_key);
            cursor = db.query(FakeDBHelper.PASSWORD_TABLE_NAME, PASSWORD_COLUMNS, null, null,
                    null, null, null);
            if(cursor.getCount() > 0) {
                cursor.move(1);
                password = cursor.getString(0);
            }
        }catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        }finally {
            close(cursor, db);
        }
        return password;
    }

    // 更新密码
    public void updateLoginPassword(String old_passwork,String new_password) {
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getWritableDatabase(db_key);
            cursor = db.query(FakeDBHelper.PASSWORD_TABLE_NAME, ID_COL_PROJECTION,
                    FakeDBHelper.LOGIN_PASSWORD + "='" + old_passwork + "'", null,
                    null, null, null);
            if(cursor.getCount() > 0) {
                cursor.move(1);
                ContentValues values = new ContentValues();
                values.put(FakeDBHelper.LOGIN_PASSWORD, new_password);
                db.update(FakeDBHelper.PASSWORD_TABLE_NAME, values,
                        FakeDBHelper.ID_COL + '=' + cursor.getString(0), null);
            }
        } catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        }finally {
            close(cursor, db);
        }
    }

    // 验证是否有记录
    public boolean hasMenoItems() {
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getReadableDatabase(db_key);
            cursor = db.query(FakeDBHelper.TABLE_NAME, COUNT_COLUMN, null,
                    null, null, null, null);
            cursor.moveToFirst();
            return cursor.getInt(0) > 0;
        } catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
            return false;
        }finally {
            close(cursor, db);
        }
    }

    // 获取所有记录信息
    public List<MenoItem> buildMenoItems() {
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        List<MenoItem> items = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getReadableDatabase(db_key);
            cursor = db.query(FakeDBHelper.TABLE_NAME, COLUMNS, null, null,
                    null, null, FakeDBHelper.TIMESTAMP_COL + " DESC");
            while (cursor.moveToNext()) {
                String title = cursor.getString(0);
                long timestamp = cursor.getLong(1);
                String details = cursor.getString(2);
                items.add(new MenoItem(title, timestamp, details));
            }
        }catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        } finally {
            close(cursor, db);
        }
        return items;
    }

    // 删除一条记录
    public void deleteMenoItem(MenoItem item) {
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getWritableDatabase(db_key);
            cursor = db.query(FakeDBHelper.TABLE_NAME, ID_COL_PROJECTION,
                    FakeDBHelper.TIMESTAMP_COL + "='" + item.getTimestamp() + "'", null,
                    null, null, FakeDBHelper.TIMESTAMP_COL + " DESC");
            cursor.move(1);
            db.delete(FakeDBHelper.TABLE_NAME,
                    FakeDBHelper.ID_COL + '=' + cursor.getString(0), null);
        }catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        } finally {
            close(cursor, db);
        }
    }

    // 更新详细
    public void updateMenoItemDetails(MenoItem item,String details) {
        updateMenoItemSingle(item,FakeDBHelper.DETAILS_COL,details);
    }

    // 更新标题
    public void updateMenoItemTitle(MenoItem item,String title) {
        updateMenoItemSingle(item,FakeDBHelper.TITLE_COL,title);
    }

    // 更新时间
    public void updateMenoItemTimestamp(MenoItem item,String timestamp) {
        updateMenoItemSingle(item,FakeDBHelper.TIMESTAMP_COL,timestamp);
    }

    // 更新某一项信息
    public void updateMenoItemSingle(MenoItem item,String update_place,String updata_content) {
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getWritableDatabase(db_key);
            cursor = db.query(FakeDBHelper.TABLE_NAME, ID_COL_PROJECTION,
                    FakeDBHelper.TIMESTAMP_COL + "='" + item.getTimestamp() + "'", null,
                    null, null, FakeDBHelper.TIMESTAMP_COL + " DESC");
            cursor.move(1);
            ContentValues values = new ContentValues();
            values.put(update_place, updata_content);
            db.update(FakeDBHelper.TABLE_NAME, values,
                    FakeDBHelper.ID_COL + '=' + cursor.getString(0), null);
        }catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        } finally {
            close(cursor, db);
        }
    }

    // 更新整条记录
    public void updateMenoItem(MenoItem olditem,MenoItem newitem) {
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = helper.getWritableDatabase(db_key);
            cursor = db.query(FakeDBHelper.TABLE_NAME, ID_COL_PROJECTION,
                    FakeDBHelper.TIMESTAMP_COL + "='" + olditem.getTimestamp() + "'", null,
                    null, null, FakeDBHelper.TIMESTAMP_COL + " DESC");
            cursor.move(1);
            ContentValues values = new ContentValues();
            values.put(FakeDBHelper.TITLE_COL, newitem.getTitle());
            values.put(FakeDBHelper.DETAILS_COL, newitem.getDetails());
            values.put(FakeDBHelper.TIMESTAMP_COL, newitem.getTimestamp());
            db.update(FakeDBHelper.TABLE_NAME, values,
                    FakeDBHelper.ID_COL + '=' + cursor.getString(0), null);
        }catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        } finally {
            close(cursor, db);
        }
    }

    // 添加一条记录
    public void addMenoItem(MenoItem item) {
        ContentValues values = new ContentValues();
        values.put(FakeDBHelper.TITLE_COL, item.getTitle());
        values.put(FakeDBHelper.DETAILS_COL, item.getDetails());
        values.put(FakeDBHelper.TIMESTAMP_COL, item.getTimestamp());

        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase(db_key);
            // Insert the new entry into the DB.
            db.insert(FakeDBHelper.TABLE_NAME, FakeDBHelper.TIMESTAMP_COL, values);
        } catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        }finally {
            close(null, db);
        }
    }

    // 清楚所有记录
    public void clearAll() {
        SQLiteOpenHelper helper = new FakeDBHelper(activity);
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase(db_key);
            db.delete(FakeDBHelper.TABLE_NAME, null, null);
        } catch (SQLiteException sqliteException){
            // // TODO: 2016/4/29
            new AlertDialog.Builder(activity).setTitle("数据库密码错误").show();
        }finally {
            close(null, db);
        }
    }

    // 关闭查询
    private static void close(Cursor cursor, SQLiteDatabase database) {
        if (cursor != null) {
            cursor.close();
        }
        if (database != null) {
            database.close();
        }
    }
}
